import React, { useState, useCallback, useEffect, useMemo, forwardRef, useImperativeHandle, useRef } from "react";
import { useTablePipeline, features, BaseTable } from "ali-react-table";
import { Checkbox, Menu, Radio, Empty }  from "antd";
import TableFooter from "./TableFooter";
import { useMultiSelect } from "./hooks/useMultiSelect";

const filterCols = d => {
	return d
		.filter(e => !(e.checked === false || e.hidden === true))
		.map(e => {
			const width = e.width === "auto" ? undefined : e.width || 120;

			const title = e.title ? (
				typeof e.title === "function" ? (
					e.title()
				) : (
					e.title
				)
			) : typeof e.name === "string" ? (
				<span>{e.name}</span>
			) : typeof e.name === "function" ? (
				e.name()
			) : (
				e.name
			);
			return {
				...e,
				width,
				title
			};
		});
};
/**
 * @param {*} tableKey
 * @param {*} dataSource
 * @param {*} columns
 * @param {*} hasPagination
 * @param {*} paginationProps
 * @param {*} footerDataSource
 * @returns
 */
export const SimpleTable = React.memo(
	forwardRef(function (
		{ tableKey, rowKey = "id", dataSource, columns, hasPagination, paginationProps, footerDataSource, className, ...restProps },
		ref
	) {
		const ComponentName = "SimpleTable";
		if (!tableKey) return <>{`${ComponentName},需要提供 tableKey`}</>;
		useEffect(() => {
			console.warn(`${ComponentName},初始化`);
		}, []);

		return (
			<>
				<BaseTable
					className={"views-virtual-table " + className}
					footerDataSource={footerDataSource}
					dataSource={dataSource}
					columns={filterCols(columns)}
					components={{ EmptyContent: Empty }}
					{...restProps}
				/>

				{hasPagination && <TableFooter {...(paginationProps || {})} />}
			</>
		);
	})
);

/**
 * @param {*} tableKey
 * @param {*} dataSource
 * @param {*} columns
 * @param {*} hasPagination
 * @param {*} paginationProps
 * @param {*} footerDataSource
 * @param {*} nextPipeline 其它拓展功能，如排序  nextPipeline = (pipeline)=> pipeline.use(features.sort({ columnKey: 'id', order: 'descend' }));
 * @param {*} getRowsByIds 默认根据咯一rowKey返回行数据
 * @param {*} onChange (selectedRowKeys,selectedRows)=> void
 * @returns
 */
export const SelectTable = React.memo(
	forwardRef(function (
		{
			className,

			type,
			//
			tableKey,
			rowKey = "id",
			dataSource = [],
			columns,
			// sortProps,
			hasPagination,
			paginationProps,
			tableFooter,
			footerDataSource,
			//
			columnResize,
			nextPipeline,
			getRowsByIds,
			onChange,
			getRowProps,
			style
		},
		ref
	) {
		const ComponentName = "SelectTable";
		if (!tableKey) return <>{`${ComponentName},需要提供 tableKey`}</>;
		useEffect(() => {
			console.warn(`${ComponentName},初始化`);
		}, []);
		///////////
		let pipeline = useTablePipeline({ components: { Checkbox, Radio } })
			.input({ dataSource: dataSource, columns: filterCols(columns) })
			// .use(features.sort({ ...sortProps }))
			.primaryKey(rowKey);

		const [openKeys, setOpenKeys] = useState([]);
		if (type === "treeSelect") {
			pipeline = pipeline.use(
				features.treeMode({
					openKeys,
					onChangeOpenKeys: async (nextKeys, key, action) => {
						setOpenKeys(nextKeys);
					}
				})
			);
		}
		const {
			multiSelectProps,
			singleSelectProps,
			treeSelectProps,
			columnResizeProps,
			clearTableSelected,
			setTableSelect,
			checkedIds
		} = useMultiSelect({
			rowKey,
			dataSource,
			footerDataSource,
			getRowsByIds,
			onChange
		});

		const tableFeature =
			type === "checkbox"
				? features.multiSelect({
						...multiSelectProps
					})
				: type === "radio"
					? features.singleSelect({
							...singleSelectProps
						})
					: type === "treeSelect"
						? features.treeSelect({ ...treeSelectProps })
						: null;

		pipeline = pipeline.use(tableFeature);

		if (columnResize) {
			pipeline = pipeline.use(features.columnResize({ ...columnResizeProps }));
		}
		// 其它拓展功能，如排序  nextPipeline = (pipeline)=> pipeline.use(features.sort({ columnKey: 'id', order: 'descend' }));
		if (typeof nextPipeline === "function") pipeline = nextPipeline(pipeline);

		const getSelectedRowKeys = () => {
			return checkedIds;
		};

		useImperativeHandle(ref, () => ({
			// 暴露给父组件的方法
			clearTableSelected,
			setTableSelect,
			getSelectedRowKeys,
			name: "SelectTable"
		}));
		return (
			<>
				<BaseTable
					className={"views-virtual-table 999 tableTotal " + className}
					{...pipeline.getProps()}
					footerDataSource={footerDataSource}
					getRowProps={getRowProps}
					components={{ EmptyContent: Empty }}
					style={style}
				/>
				{tableFooter}

				{hasPagination && <TableFooter {...(paginationProps || {})} />}
			</>
		);
	})
);

/**
 * 继承 SelectTable
 */
export const CheckboxTable = React.memo(
	forwardRef(function (props, ref) {
		const ComponentName = "CheckboxTable";
		useEffect(() => {
			console.warn(`${ComponentName},初始化`);
		}, []);

		const RefSelectTable = useRef(null);
		useImperativeHandle(ref, () => ({
			// 暴露给父组件的方法
			RefSelectTable: RefSelectTable.current,
			name: "CheckboxTable",
			...(RefSelectTable.current || {})
		}));

		return <SelectTable ref={RefSelectTable} type="checkbox" {...props} children={<>测试</>} onToggle={() => {}} />;
	})
);

/**
 * 继承 SelectTable
 */
export const RadioTable = React.memo(
	forwardRef(function (props, ref) {
		const ComponentName = "RadioTable";
		useEffect(() => {
			console.warn(`${ComponentName},初始化`);
		}, []);

		const RefRadioTable = useRef(null);
		useImperativeHandle(ref, () => ({
			// 暴露给父组件的方法
			RefRadioTable: RefRadioTable.current,
			name: "RefRadioTable",
			...(RefRadioTable.current || {})
		}));

		return <SelectTable ref={RefRadioTable} type="radio" {...props} />;
	})
);

/**
 * 继承 SelectTable
 */
export const TreeSelectTable = React.memo(
	forwardRef(function (props, ref) {
		const ComponentName = "TreeSelectTable";
		useEffect(() => {
			console.warn(`${ComponentName},初始化`);
		}, []);

		const RefTreeTable = useRef(null);
		useImperativeHandle(ref, () => ({
			// 暴露给父组件的方法
			RefTreeTable: RefTreeTable.current,
			name: "TreeSelectTable",
			...(RefTreeTable.current || {})
		}));

		return <SelectTable ref={RefTreeTable} type="treeSelect" {...props} />;
	})
);
